package com.farm.area.controller;

import com.farm.area.pojo.FarmArea;
import com.farm.area.service.FarmAreaService;
import com.farm.constant.MessageConstant;
import com.farm.entity.PageResult;
import com.farm.entity.Result;
import com.farm.entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 农场片区
 * @author azhe
 * @create 2020/10/10
 */
@RestController
@CrossOrigin
@RequestMapping("/farmArea")
public class FarmAreaController {

    @Autowired
    private FarmAreaService farmAreaService;

    /**
     * 查询所有片区
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll(){
        List<Map<String, Object>> farmAreaList = farmAreaService.findAll();
        if(farmAreaList == null || farmAreaList.size() == 0){
            return new Result(false, StatusCode.ERROR, MessageConstant.SELECT_FARM_AREA_FAIL);
        }
        return new Result(true, StatusCode.OK, MessageConstant.SELECT_FARM_AREA_SUCCESS,farmAreaList);
    }

    /**
     * 添加片区
     * @param farmArea
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody FarmArea farmArea){
        try {
            farmAreaService.add(farmArea);
            return new Result(true,StatusCode.OK,MessageConstant.ADD_FARM_AREA_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,MessageConstant.ADD_FARM_AREA_FAIL);
        }
    }

    /**
     * 修改片区
     * @param farmArea
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody FarmArea farmArea){
        try {
            farmAreaService.update(farmArea);
            return new Result(true,StatusCode.OK,MessageConstant.UPDATE_FARM_AREA_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,MessageConstant.UPDATE_FARM_AREA_FAIL);
        }
    }

    /**
     * 根据id删除片区
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Integer id){
        try {
            farmAreaService.delete(id);
            return new Result(true,StatusCode.OK,MessageConstant.DELETE_FARM_AREA_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,MessageConstant.DELETE_FARM_AREA_FAIL);
        }
    }

    /**
     * 分页条件查询
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/findPage")
    public PageResult findPage(@RequestParam(name = "page",required = false,defaultValue = "1") Integer page,
                               @RequestParam(name = "size",required = false,defaultValue = "10") Integer size,
                               @RequestParam(required = false) Map searchMap){
        return farmAreaService.findPage(page,size,searchMap);
    }
}
